import logging
import requests
import json

class AIModels:
    def __init__(self, config):
        self.config = config

    def call_wenxin_ai(self, messages, temperature, max_tokens):
        api_url = "https://api.wenxin.baidu.com/v1/completions"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.config.API_KEY}"
        }
        payload = {
            "model": "wenxin",
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }

        try:
            response = requests.post(api_url, headers=headers, json=payload)
            response.raise_for_status()
            result = response.json()
            logging.info("Wenxin AI response: %s", result)
            if result.get("choices"):
                return result["choices"][0]["message"]["content"]
            else:
                return "API返回的结果为空，可能是请求参数有误或者服务暂时不可用。"
        except requests.exceptions.RequestException as e:
            logging.error("Wenxin AI API call error: %s", str(e))
            return f"API调用失败，错误信息: {str(e)}"

    def call_spark_ai(self, messages, temperature, max_tokens):
        api_url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.config.XUNFEI_API_KEY}:{self.config.XUNFEI_SECRET_KEY}"
        }
        payload = {
            "model": "generalv3.5",
            "messages": messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }

        try:
            response = requests.post(api_url, headers=headers, json=payload)
            response.raise_for_status()
            result = response.json()
            logging.info("Spark AI response: %s", result)
            if result.get("choices"):
                return result["choices"][0]["message"]["content"]
            else:
                return "API返回的结果为空，可能是请求参数有误或者服务暂时不可用。"
        except requests.exceptions.RequestException as e:
            logging.error("Spark AI API call error: %s", str(e))
            return f"API调用失败，错误信息: {str(e)}"

    def call_qwen_ai(self, messages, temperature, max_tokens):
        api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.config.QIANWEN_API_KEY}",
            "X-DashScope-SSE": "enable"
        }
        payload = {
            "model": "qwen2-72b-instruct",
            "input": {
                "messages": messages
            },
            "parameters": {
                "temperature": temperature,
                "max_tokens": max_tokens
            }
        }

        try:
            logging.info("Sending request to Qwen AI")
            response = requests.post(api_url, json=payload, headers=headers)
            response.encoding = 'utf-8'

            if response.status_code == 200:
                events = response.text.strip().split("\n\n")
                final_results = []

                for event in events:
                    try:
                        for line in event.split("\n"):
                            if line.startswith("data:"):
                                json_data = line[len("data:"):]
                                data = json.loads(json_data)
                                final_results.append(data)
                    except json.JSONDecodeError as e:
                        logging.error("JSON Decode Error in event: %s", str(e))
                        logging.debug("Event data: %s", event)

                logging.info("All parsed results: %s", json.dumps(final_results, indent=4))

                full_text = ""
                for result in final_results:
                    if result.get("output", {}).get("finish_reason") == "stop":
                        full_text = result.get("output", {}).get("text", "")
                        break
                    else:
                        full_text += result.get("output", {}).get("text", "")

                return full_text
            else:
                logging.error("Non-OK HTTP status code received: %d %s", response.status_code, response.text)
                return "请求失败，HTTP状态码: " + str(response.status_code)

        except requests.exceptions.RequestException as e:
            logging.error("Qwen API call error: %s", str(e))
            return f"API调用失败，错误信息: {str(e)}"
        except Exception as e:
            logging.error("Unexpected error: %s", str(e))
            return f"发生未知错误: {str(e)}"